/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function(nums, k) {
  let map = new Map();
  for(let i = 0; i < nums.length; i++) {
    if(!map.get(nums[i])) {
      map.set(nums[i], 1);
    } else {
      map.set(nums[i], map.get(nums[i]) + 1);
    }
  }
  let arr = [];
  for(let item of map) {
    arr.push({
      index: item[0],
      value: item[1]
    });
  }
  arr = arr.sort((a, b) => {
    return b.value - a.value;
  });
  let result = [];
  for(let i = 0; i < k; i++) {
    result.push(arr[i].index);
  }
  return result;
};
let nums = [1,1,1,2,2,3], k = 2;
console.log(topKFrequent(nums, k));
nums = [1], k = 1;
console.log(topKFrequent(nums, k));
